package com.wholesale;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ViewFlipper;

import com.wholesale.utils.Constants;

public class MoreActivity extends Activity {
	private ViewFlipper viewFlipper;
	DataReceiver dataReceiver;// BroadcastReceiver对象
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Constants.initMoreActivity = true ;
		viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
		MoreLayout moreLayout = new MoreLayout(this, viewFlipper);
		viewFlipper.addView(moreLayout);
		if(Constants.toMyAccount){
			MyAccountLayout myAccountLayout = new MyAccountLayout(this, viewFlipper);
			viewFlipper.addView(myAccountLayout);
			viewFlipper.showNext();
		}
	}

	private class DataReceiver extends BroadcastReceiver {// 继承自BroadcastReceiver的子类
		@Override
		public void onReceive(Context context, Intent intent) {
			int cmd = intent.getIntExtra("cmd", -1);// 获取Extra信息
			if(cmd == Constants.CMD_ADDFAVORITE_SERVICE){ //更新收藏页面
				if(viewFlipper.getCurrentView().getClass().getName().equals(MyFavoritesLayout.class.getName())){
					 ((MyFavoritesLayout)viewFlipper.getCurrentView()).reLoad();
				}
			}else{
				viewFlipper.removeAllViews();
				viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
				MoreLayout moreLayout = new MoreLayout(MoreActivity.this, viewFlipper);
				viewFlipper.addView(moreLayout);
				if(Constants.toMyAccount){
					MyAccountLayout myAccountLayout = new MyAccountLayout(MoreActivity.this, viewFlipper);
					viewFlipper.addView(myAccountLayout);
					viewFlipper.showNext();
				}
			}
		}
	}
	
	@Override
	protected void onStart() {// 重写onStart方法
		dataReceiver = new DataReceiver();
		IntentFilter filter = new IntentFilter();// 创建IntentFilter对象
		filter.addAction("com.wholesale.MoreActivity");
		registerReceiver(dataReceiver, filter);// 注册Broadcast Receiver
		super.onStart();
	}

	@Override
	protected void onStop() {// 重写onStop方法
		unregisterReceiver(dataReceiver);// 取消注册Broadcast Receiver
		super.onStop();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(viewFlipper.getChildCount()>1){
				viewFlipper.showPrevious();
				viewFlipper.removeViewAt(viewFlipper.getChildCount()-1);
				return true ;
			}else{
				return false ;
			}
		}else{
			return super.onKeyDown(keyCode, event);
		}
	}
}
